<template>
	<div class="q-pa-md">
		{{ aaa }}
		<q-table title="CRM员工明细表" :rows="filteredRows" :columns="columns" :pagination="paginationOptions"
			:loading="loading" row-key="name" title-class="rainbow-title" bordered flat>

			<template v-slot:top-right>
				<div class="row q-gutter-sm q-mb-md">
					<!-- 新增按钮 -->
					<q-btn color="primary" icon="add" label="新增人员" @click="openAddDialog" class="q-px-md" />
					<q-btn color="primary" icon="add" label="测试按钮" @click="cs" class="q-px-md" />
					<!-- 原有筛选输入框 -->
					<q-input v-model="filterName" outlined dense placeholder="输入姓名筛选" class="search-input"
						label-color="primary" input-class="text-primary" clearable>
						<template v-slot:prepend>
							<q-icon name="person" color="primary" />
						</template>
						<template v-slot:append>
							<q-icon name="search" color="primary" />
						</template>
					</q-input>

					<q-input v-model="filterDep" outlined dense placeholder="输入部门筛选" class="search-input"
						label-color="primary" input-class="text-primary" clearable>
						<template v-slot:prepend>
							<q-icon name="apartment" color="primary" />
						</template>
						<template v-slot:append>
							<q-icon name="search" color="primary" />
						</template>
					</q-input>
				</div>
			</template>


			<template v-slot:header-cell-userName="props">
				<q-th :props="props" class="text-h6 text-primary text-weight-bold header-border">
					<div class="column items-center">
						<q-icon name="person" class="q-mb-xs" />
						{{ props.col.label }}
					</div>
				</q-th>
			</template>

			<template v-slot:header-cell-postName="props">
				<q-th :props="props" class="text-h6 text-primary text-weight-bold header-border">
					<div class="column items-center">
						<q-icon name="work" class="q-mb-xs" />
						{{ props.col.label }}
					</div>
				</q-th>
			</template>

			<template v-slot:header-cell-depName="props">
				<q-th :props="props" class="text-h6 text-primary text-weight-bold header-border">
					<div class="column items-center">
						<q-icon name="apartment" class="q-mb-xs" />
						{{ props.col.label }}
					</div>
				</q-th>
			</template>

			<template v-slot:header-cell-jzDep="props">
				<q-th :props="props" class="text-h6 text-primary text-weight-bold header-border">
					<div class="column items-center">
						<q-icon name="business" class="q-mb-xs" />
						{{ props.col.label }}
					</div>
				</q-th>
			</template>

			<!-- 新增头像显示模板 -->
			<template v-slot:body-cell-userName="props">
				<q-td :props="props">
					<div class="row items-center no-wrap">
						<q-avatar size="32px" class="q-mr-sm shadow-10">
							<img :src="props.row.avatar || 'https://cdn.quasar.dev/img/avatar.png'">
						</q-avatar>
						<span>{{ props.row.userName }}</span>
					</div>
				</q-td>
			</template>

			<!-- 新增岗位编辑模板 -->
			<template v-slot:body-cell-postName="props">
				<q-td :props="props">
					<q-badge color="blue" outline class="text-h7">
						{{ props.row.postName }}
					</q-badge>
					<q-popup-edit v-model="props.row.postName" title="选择或输入岗位" v-slot="scope">
						<div class="q-gutter-sm">
							<q-select v-model="scope.value" use-input fill-input hide-selected input-debounce="300"
								:options="postOptions" option-label="name" option-value="id" emit-value map-options
								@filter="filterPosts" style="min-width: 250px" dense autofocus>
								<!-- 新增无匹配提示 -->
								<template v-slot:no-option>
									<q-item>
										<q-item-section class="text-grey-6">
											没有匹配的岗位
										</q-item-section>
									</q-item>
								</template>
							</q-select>

							<div class="row justify-end q-mt-sm">
								<q-btn flat dense color="negative" icon="cancel" @click="scope.cancel" />
								<q-btn flat dense color="positive" icon="check_circle"
									@click="validatePost(scope, props)" />
							</div>
						</div>
					</q-popup-edit>
				</q-td>
			</template>

			<!-- 新增部门编辑模板 -->
			<template v-slot:body-cell-depName="props">
				<q-td :props="props">
					<q-badge color="indigo" outline>
						{{ props.row.depName }}
					</q-badge>
					<q-popup-edit v-model="props.row.depName" title="选择或输入部门" v-slot="scope">
						<div class="q-gutter-sm">
							<q-select v-model="scope.value" use-input fill-input hide-selected input-debounce="300"
								:options="depOptions" option-label="name" option-value="id" emit-value map-options
								@filter="filterDeps" style="min-width: 250px" dense autofocus>
								<!-- 新增无匹配提示 -->
								<template v-slot:no-option>
									<q-item>
										<q-item-section class="text-grey-6">
											没有匹配的部门
										</q-item-section>
									</q-item>
								</template>
							</q-select>

							<div class="row justify-end q-mt-sm">
								<q-btn flat dense color="negative" icon="cancel" @click="scope.cancel" />
								<q-btn flat dense color="positive" icon="check_circle"
									@click="validateDep(scope, props)" />
							</div>
						</div>
					</q-popup-edit>
				</q-td>
			</template>

			<template v-slot:no-data>
				<div class="full-width row flex-center text-negative q-gutter-sm">
					<q-icon name="warning" />
					<span>暂无可用数据</span>
				</div>
			</template>

			<template v-slot:body-cell-jzDep="props">
				<q-td :props="props">
					<div class="q-gutter-xs">
						<q-badge v-for="(dep, index) in props.row.jz" :key="index" color="teal" outline>
							{{ dep.depName }}
						</q-badge>
					</div>
				</q-td>
			</template>

		</q-table>
	</div>

	<q-dialog v-model="confirm" persistent>
		<q-card>
			<q-card-section class="row items-center">
				<q-form @submit="onSubmit" class="q-gutter-md">
					<q-input filled v-model="renyuan.name" label="Your name *" hint="Name and surname" lazy-rules
						:rules="[val => val && val.length > 0 || 'Please type something']" />
						<q-input filled v-model="renyuan.position" label="Your name *" hint="Name and surname" lazy-rules
						:rules="[val => val && val.length > 0 || 'Please type something']" />
						<q-input filled v-model="renyuan.status" />
						<!-- 添加部门选择 -->
						<q-select v-model="renyuan.bm" use-input fill-input hide-selected input-debounce="300"
								:options="depOptions" option-label="name" option-value="id" emit-value map-options
								@filter="filterDeps" style="min-width: 250px" dense autofocus>
								<!-- 新增无匹配提示 -->
								<template v-slot:no-option>
									<q-item>
										<q-item-section class="text-grey-6">
											没有匹配的部门
										</q-item-section>
									</q-item>
								</template>
							</q-select>

				<!-- 添加岗位选择 -->
				<q-select v-model="renyuan.gw" use-input fill-input hide-selected input-debounce="300"
								:options="postOptions" option-label="name" option-value="id" emit-value map-options
								@filter="filterPosts" style="min-width: 250px" dense autofocus>
								<!-- 新增无匹配提示 -->
								<template v-slot:no-option>
									<q-item>
										<q-item-section class="text-grey-6">
											没有匹配的岗位
										</q-item-section>
									</q-item>
								</template>
							</q-select>
					<q-btn label="Submit" type="submit" color="primary" />
					<q-btn flat label="取消" color="primary" v-close-popup />
				</q-form>
			</q-card-section>
		</q-card>
	</q-dialog>
</template>

<script>

//企业微信 JS-SDK
import * as ww from '@wecom/jssdk'

// 提取常量为独立声明
const TABLE_COLUMNS = [
	{
		name: "userName",
		label: "姓名",
		field: "userName",
		align: "center",
		sortable: true,
	},
	{
		name: "postName",
		label: "岗位",
		field: "postName",
		align: "center",
		sortable: true,
	},
	{
		name: "depName",
		label: "部门",
		field: "depName",
		align: "center",
		sortable: true,
	},
	{
		name: "jzDep",
		label: "兼职部门",
		field: row => row.jz?.map(d => d.DepName).join(', ') || '', // 处理数组数据
		align: "center",
		sortable: true
	}
];

export default {
	data() {
		return {
			renyuan: {},
			confirm: false,
			aaa: '',
			paginationOptions: {
				rowsPerPage: 10,
			},
			allData: [],
			columns: TABLE_COLUMNS, // 使用常量定义
			rows: [],
			loading: false,
			allPosts: [],  // 新增原始数据存储
			postOptions: [],
			depOptions: [],
			allDeps: [],  // 新增原始数据存储
			filterName: '',
			filterPost: null,
			filterDep: null,
			departments: []
		};
	},
	computed: {
		filteredRows() {
			return this.rows.filter(item =>
				(item.userName || '').toLowerCase().includes((this.filterName || '').toLowerCase()) &&
				(item.depName || '').toLowerCase().includes((this.filterDep || '').toLowerCase())
			)
		}
	},
	methods: {
		async onSubmit() {
			// 提交表单逻辑
			console.log('提交表单:', { data: this.renyuan });
			// 这里可以添加实际的提交逻辑，如API调用
			// 提交完成后，关闭弹窗
			// 提交表单逻辑
			await this.$API.crm.SaveUserInfo.post(this.renyuan).then(res => {
				console.log(res);
				// if (res.err_code === 0) {
				// 	this.$q.notify({
				// 		type: 'positive',
				// 		message: '添加成功',
				// 		position: 'top'
				// 	})
				// 	this.confirm = false;

				// } else {
				// 	this.$q.notify({
				// 		type: 'negative',
				// 		message: res.err_msg,
				// 		position: 'top'
				// 	})
				// }
			})
			this.confirm = false;
		},
		async cs() {
			this.confirm = true;
			this.loading = true;
			this.renyuan = await this.$API.crm.GetUserInfo.get('liqm');
			this.loading = false;
			console.log(this.renyuan);
		},
		// 在methods中添加新方法
		openAddDialog() {
			// this.$q.dialog({
			// 	title: '新增人员',
			// 	message: '人员信息录入表单待实现', // 需要替换为实际表单组件
			// 	persistent: true
			// }).onOk(() => {
			// 	// 这里添加调用API的逻辑
			// 	// 示例：await this.$API.crm.AddUser.post(formData)
			// })
			ww.selectEnterpriseContact({
				fromDepartmentId: -1,
				mode: 'single',
				type: ['user']
			}).then(res => {
				if (res.err_code === 0) {
					var userList = res.result.userList;
					var user = userList[0];
					this.$q.dialog({
						title: user.avatar,
						message: user.id, // 需要替换为实际表单组件
						persistent: true
					}).onOk(async () => {
						// 这里添加调用API的逻辑
						// 示例：await this.$API.crm.AddUser.post(formData)
						this.confirm = true;
						this.loading = true;
						this.renyuan = await this.$API.crm.GetUserInfo.get(user.id);
						this.loading = false;
					})
				}   // 已选成员列表
			}).catch(err => {
				console.error('选择失败:', err);
			});
		},
		async validatePost(scope, props) {
			// 通过名称查找完整岗位对象
			const postObj = this.allPosts.find(p => p.id === scope.value)
			if (postObj) {
				scope.value = postObj.name
				scope.set()
				this.loading = true;
				await this.$API.crm.UpPost.put(props.row.id, postObj.id)
				this.loading = false;
			} else {
				this.$q.notify({
					type: 'negative',
					message: '请输入有效的岗位名称',
					position: 'top'
				})
			}
		},

		filterPosts(val, update) {
			update(() => {
				const needle = val.toLowerCase()
				this.postOptions = this.allPosts.filter(v =>
					v.name.toLowerCase().includes(needle)  // 修改过滤条件为对象属性
				)
			})
		},

		async validateDep(scope, props) {
			const depObj = this.allDeps.find(p => p.id === scope.value)
			if (depObj) {
				scope.value = depObj.name
				scope.set()
				this.loading = true;
				await this.$API.crm.UpDep.put(props.row.id, depObj.id, props.row.postId, props.row.oldDepId)
				this.loading = false;
				props.row.oldDepId = depObj.id;
			} else {
				this.$q.notify({
					type: 'negative',
					message: '请输入有效的部门名称',
					position: 'top'
				})
			}
		},

		filterDeps(val, update) {
			update(() => {
				const needle = val.toLowerCase()
				this.depOptions = this.allDeps.filter(v =>
					v.name.toLowerCase().includes(needle)  // 修改过滤条件为对象属性
				)
			})
		},

		showError(msg, error) {
			this.$q.notify({
				type: 'negative',
				message: `${msg}: ${error.message}`,
				position: 'top',
				timeout: 2000
			});
		}
	},
	watch: {
	},
	async mounted() {
		try {
			this.loading = true;  // 控制表格加载状态
			const JSAPI_TICKET = await this.$API.weixin.GetJsapiTicket.get("0");
			console.log(JSAPI_TICKET);
			ww.register({
				corpId: 'wx60fb60c92a367e5d',
				jsApiList: ['selectEnterpriseContact'],
				getConfigSignature() {
					return ww.getSignature(JSAPI_TICKET)
				}
			})
			// 并行请求
			const [users, posts, deps] = await Promise.all([
				this.$API.crm.GetBaseUser.get(),
				this.$API.crm.GetBasePost.get(),
				this.$API.crm.GetBaseDep.get()
			]);

			this.rows = users || [];
			this.allPosts = posts || [];
			this.allDeps = deps || [];
			this.postOptions = [...this.allPosts];
			this.depOptions = [...this.allDeps];
			//console.log(this.rows)
		} catch (error) {
			this.showError('数据加载失败', error);
		} finally {
			this.loading = false;
		}
	}
}
</script>

<style lang="scss">
.q-table__container {
	tr {
		margin: 8px 0;
		transition: transform 0.3s ease;

		&:hover {
			transform: translateX(8px);
		}

		td {
			background: white !important;
			border-bottom: 1px solid rgba(0, 0, 0, 0.05);
			box-shadow: 0 2px 8px rgba(0, 0, 0, 0.03);
		}
	}
}

.search-input {
	width: 240px;
	transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);

	.q-field__control {
		border-radius: 12px;
		background: rgba(255, 255, 255, 0.9);

		&:before {
			border-color: rgba(25, 118, 210, 0.3);
		}

		&:hover:before {
			border-color: #1976d2;
		}
	}

	&.q-field--focused {
		.q-field__control {
			box-shadow: 0 4px 12px rgba(25, 118, 210, 0.2);
			background: white;

			&:after {
				transform: scaleX(1);
				opacity: 1;
			}
		}
	}

	.q-icon {
		transition: transform 0.3s ease;
	}

	&:hover .q-icon {
		transform: scale(1.1);
	}
}

.header-border {
	border-bottom: 3px solid #1976d2;
	padding: 12px 16px;
	transition: all 0.3s ease;

	&:hover {
		background: #e3f2fd;
		transform: translateY(-2px);
	}

	.q-icon {
		font-size: 1.4em;
	}
}

.rainbow-title {
	background: linear-gradient(90deg,
			#ff0000 0%,
			#ff9900 20%,
			#33cc33 40%,
			#3399ff 60%,
			#cc33ff 80%,
			#ff0066 100%);
	-webkit-background-clip: text;
	color: transparent;
	animation: rainbow 2s linear infinite;
}

@keyframes rainbow {
	to {
		background-position: 200% center;
	}
}

.q-table__container {
	box-shadow: 0 2px 15px rgba(0, 0, 0, 0.1);

	tr:hover {
		background-color: #f5f7fa;
	}
}
</style>